<template>
  <div class="message-list" ref="messageListRef">
    <div
      v-for="(message, index) in messages"
      :key="index"
      :class="['message', message.type]"
    >
      <div class="message-content">
        <vue-markdown-render :source="message.content" />
      </div>
      <div class="message-time">
        {{ formatTime(message.timestamp) }}
      </div>
    </div>
    
    <!-- 思考中提示 -->
    <div v-if="isThinking" class="message assistant thinking">
      <div class="message-content">
        <div class="thinking-indicator">
          <div class="thinking-dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
          <span class="thinking-text">AI正在思考中...</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, watch, onMounted } from 'vue'
import VueMarkdownRender from 'vue-markdown-render'
import { formatTime } from '@/utils/time'

const props = defineProps<{
  messages: Array<{
    type: 'user' | 'assistant'
    content: string
    timestamp?: string
  }>
  isThinking?: boolean
}>()

const messageListRef = ref<HTMLElement>()

// 滚动到底部的方法
const scrollToBottom = async () => {
  await nextTick()
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

// 监听消息变化，自动滚动到底部
watch(() => [props.messages, props.isThinking], () => {
  scrollToBottom()
}, { deep: true })

// 组件挂载后滚动到底部
onMounted(() => {
  scrollToBottom()
})

// 暴露滚动方法给父组件
defineExpose({
  scrollToBottom
})
</script>

<style scoped>
.message-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
  overflow-y: auto;
  scroll-behavior: smooth;
}

.message {
  max-width: 80%;
  padding: 12px;
  border-radius: 8px;
}

.message.user {
  align-self: flex-end;
  background-color: #e6f7ff;
}

.message.assistant {
  align-self: flex-start;
  background-color: #f5f5f5;
}

.message-content {
  word-break: break-word;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

:deep(.markdown-body) {
  background: transparent;
}

/* 思考中提示样式 */
.thinking {
  opacity: 0.8;
}

.thinking-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.thinking-dots {
  display: flex;
  gap: 4px;
}

.thinking-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #1890ff;
  animation: thinking-pulse 1.4s infinite ease-in-out;
}

.thinking-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.thinking-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

.thinking-text {
  color: #666;
  font-style: italic;
}

@keyframes thinking-pulse {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>